<template>
  <div>
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" title="选择超级企微" width="1100px" modal-append-to-body>
      <NormalForm :enum-opt.sync="enumOpt" :formList="formList" :isShowCard="false"
                  :operateForm="queryForm" @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
      <div class="dialog_info">
        <i class="el-icon-warning" style="color: #082AFF;margin-right: 6px"></i>
        <span>{{ `仅显示${queryForm.status == '2' ? '离线' : '在线'}的超级企微，支持同时选择多个超级企微` }}</span>
      </div>
      <div v-if="checkedList.length > 0" class="checkList_area">
        <span style="margin-left: 12px">已选:</span>
        <div v-for="item in checkedList" :key="item.id" class="checkList_item">
          <img v-if="item.headImageUrl" :src="item.headImageUrl" alt="" class="checkList_item_avatar">
          <img v-else :src="defaultHeadImage" alt="" class="checkList_item_avatar">
          <span class="checkList_item_name">{{ item.userName }}
            <i class="el-icon-close" style="padding: 0 6px;font-size: 14px;cursor: pointer" @click="delItem(item)"></i>
          </span>
        </div>
      </div>
      <el-row class="row-radar" style="margin-top: 20px">
        <el-col :span="6">
          <div class="mt-20">
            <el-tree ref="tree" v-loading="loading" :data="treeData" :expand-on-click-node="false" :props="treeProps"
                     default-expand-all highlight-current @node-click="handleNodeClick">
              <div slot-scope="{ node, data }" class="custom-tree-node">
                <el-tooltip v-if="node.label.length > 8" :content="node.label" effect="dark" placement="bottom">
                  <span class="label-info">{{ node.label }}</span>
                </el-tooltip>
                <span v-else>{{ node.label }}</span>
              </div>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="18" style="border-left: 1px solid #eee; padding: 16px 15px 20px 15px;">
          <el-table ref="multipleTable" v-loading="loading" :data="tableList" height="442px"
                    style="width: 100%" @select="handleSelectionChange" @select-all="handleSelected">
            <el-table-column type="selection" width="55"/>
            <el-table-column align="center" label="部门" min-width="140px" prop="department"
                             show-overflow-tooltip></el-table-column>
            <el-table-column :show-overflow-tooltip="false" align="center" label="头像/昵称" min-width="200"
                             prop="alias">
              <template slot-scope="{ row }">
                <div style="display: flex;align-items: center;justify-content: center">
                  <img v-if="row.headImageUrl" :src="row.headImageUrl" alt=""
                       style="width:30px; height:30px;border-radius:50%;margin-right:6px">
                  <span style="line-height: 30px">{{ row.alias }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="企业员工" min-width="120px" prop="userName"
                             show-overflow-tooltip></el-table-column>
          </el-table>
          <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
                            @handleCurrentChange="handleCurrentChange"
                            @handleSizeChange="handleSizeChange"></NormalPagination>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleCancel">取 消</el-button>
        <el-button size="mini" type="primary" @click="ok">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "@/api/organization";
import {categoryList} from "@/api/article/group";
import {automateList} from '@/api/escrowAccount/index'

export default {
  name: 'selectSupermicroDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    isSingleOption: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    dialogVisible: {
      get() {
        if (!this.visible) this.loading = false
        if (this.visible) {
          // 初始化查询 列表 分组 员工数据
          this.handleQuery();
          this.getdialogList2()
          this.getNodeFn()
          this.checkedList = []
        }
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  data() {
    return {
      queryForm: {
        name: '',
        status: '1',
        weUserId: '',
        pageNum: 1,
        pageSize: 20,
      },
      treeData: [
        {
          id: '',
          name: '全部',
          parentId: 0,
          hasParent: false,
          hasChildren: true,
          children: []
        },
      ],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      formList: [
        {
          label: '昵称',
          value: '',
          prop: 'name',
          type: 'INPUT',
          emunName: '',
          xl: 6,
          lg: 8,
        },
        {
          label: '在线状态',
          value: '1',
          prop: 'status',
          type: 'SELECT',
          emunName: 'statesList',
          xl: 6,
          lg: 8,
        },
        {
          label: '员工',
          value: '',
          prop: 'weUserId',
          type: 'SELECT',
          emunName: 'dialogList',
          xl: 6,
          lg: 8,
        },
      ],
      enumOpt: {
        statesList: [
          {dictLabel: '在线', dictValue: '1'},
          {dictLabel: '离线', dictValue: '2'},
        ],
        dialogList: [],
      },
      loading: false,
      total: 0,
      tableList: [],
      checkedList: [],
      drainageOpt: {},
      currentGroupId: '',
      defaultHeadImage: 'https://test-ztdata-1308072185.cos.ap-shanghai-fsi.myqcloud.com/siyu/2024/04/15/202404151353039078.png?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDAalfJgmb9QRBdoiMjpeEYcPwCAsJSKvF%26q-sign-time%3D1713160384%3B4866760384%26q-key-time%3D1713160384%3B4866760384%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3Db660d3547810e985073de32d0e0afeb8b784c657',
    }
  },
  mounted() {
  },
  methods: {
    ok() {
      if (this.isSingleOption) {
        let arr = new Array()
        if (this.checkedList.length > 0) arr.push({...this.checkedList[0]})
        if(arr.length == 0) return this.$message.error('请先选择超级企微')
        this.handleCancel()
        this.$emit('supermicroUpdate', arr)
        this.$emit('update:visible', false)
      } else {
        if (this.checkedList.length == 0) return this.$message.error('请先选择超级企微')
        this.handleCancel()
        this.$emit('supermicroUpdate', this.checkedList)
        this.$emit('update:visible', false)
      }
    },
    handleSelected(val){
      if(this.isSingleOption && val && val.length > 1) return
      this.checkedList = val
      console.log('checkedList::::::', this.checkedList)
    },
    handleSelectionChange(selection, val) {
      console.log(selection, val, this.isSingleOption, '123456765')
      if (this.isSingleOption) {
        this.$refs.multipleTable.clearSelection();
        if (selection.length == 0) {
          this.selectedRow = [];  // 清空data中绑定的selectedRow
          this.checkedList = []
          return
        };
        // 切换最近一次选择数据的状态
        this.$refs.multipleTable.toggleRowSelection(val, true);
        // 更新data中的selectedRow
        this.checkedList = [{...val, id: val.automateId}];
      } else {
        selection.forEach(item => {
          console.log(item, '1')
          if (!this.checkedList.some(checkedItem => checkedItem.id === item.automateId)) {
            this.checkedList.push({ ...item, id: item.automateId });
          }
        })
      }
    },
    // 重置
    handleReset() {
      this.queryForm = {
        status: '1',
        weUserId: '',
        name: '',
        pageNum: 1,
        pageSize: 20,
      };
      this.currentGroupId = ''
      this.getListFn();
    },
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getListFn()
    },
    getListFn() {
      console.log(this.queryForm, 'queryForm')
      let obj = {
        ...this.queryForm,
        categoryId: this.currentGroupId || ''
      };
      this.loading = true;
      this.tableList = []
      this.loading = true
      automateList(obj).then(res => {
        if (res.code == 200) {
          this.tableList = res.rows
          this.$nextTick(() => {
            if (this.checkedList.length > 0 && this.tableList.length > 0) {
              this.checkedList.forEach(item => {
                this.tableList.forEach(element => {
                  console.log(element.id, item.automateId, 'element-item')
                  if (element.automateId == item.id) {
                    this.$refs.multipleTable.toggleRowSelection(element);
                  }
                })
              })
            }
          })
          this.total = res.total;
          console.log('tableList', this.tableList);
        }
      }).finally(() => this.loading = false)
    },
    // 翻页
    handleSizeChange(value) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = value
      this.getListFn()
    },
    handleCurrentChange(value) {
      this.queryForm.pageNum = value
      this.getListFn()
    },
    // 点击分组
    handleNodeClick(data) {
      this.currentGroupId = data.id
      this.getListFn()
    },
    getdialogList2() {
      if (this.enumOpt.dialogList.length == 0) {
        api.getList({
          name: '',
          department: '',
          pageNum: 1,
          pageSize: 99999,
          isActivate: '',
        })
          .then(({rows}) => {
            this.enumOpt.dialogList = rows.map(item => {
              return {
                ...item,
                dictValue: item.userId,
                dictLabel: item.name
              }
            })
            console.log(this.enumOpt.dialogList, 'dialoglist', '数组列')
          })
      }
    },
    // 获取分组数据
    getNodeFn() {
      let params = {
        levelType: '0',
        mediaType: '13',
      }
      categoryList(params).then(res => {
        if (res.code == 200) {
          this.groupTotal = res.data ? res.data.length : 0
          this.$set(this.treeData[0], 'children', res.data)
        }
      })
    },
    // 删除选中的超级企微
    delItem(item) {
      this.checkedList = this.checkedList.filter(e => e.id != item.id)
      console.log('查看列表结果::::', this.tableList.some(e => e.automateId == item.id))
      if (this.tableList.some(e => e.automateId == item.id)) {
        this.tableList.forEach(row => {
          if (row.automateId == item.id) {
            this.$refs.multipleTable.toggleRowSelection(row, false);
          }
        });
      }
    },
    // 关闭弹窗
    handleCancel(){
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

::v-deep .el-tag.el-tag--success {
  background-color: #e6f9ef !important;
  border-color: #14D595 !important;
  color: #06c160 !important;
}

::v-deep.el-tag.el-tag--info {
  background-color: #f4f4f5 !important;
  border-color: #e9e9eb !important;
  color: #909399 !important;
}

::v-deep.el-tag.el-tag--danger {
  background-color: #fdedee !important;
  border-color: #fadcde !important;
  color: #e74e59 !important;
}

::v-deep.el-tag.el-tag--warning {
  background-color: rgba(255, 173, 58, 0.1) !important;
  border-color: #FFAD3A !important;
  color: #FFAD3A !important;
}

.dialog_info {
  padding: 8px 10px;
  color: #082AFF;
  margin-bottom: 10px;
  background-color: #EBEEFF;
  border-radius: 8px;
}

.checkList_area {
  display: flex;
  flex-wrap: wrap;
  background: #F8F8F9;
  align-items: center;
  color: #505050;
  font-size: 12px;
}

.checkList_item {
  display: flex;
  line-height: 52px;
  align-items: center;
  margin-left: 12px;
  padding: 8px 0;

  .checkList_item_avatar {
    width: 36px;
    height: 36px;
  }

  .checkList_item_name {
    min-width: 58px;
    padding-left: 6px;
    background-color: #fff;
    height: 36px;
    line-height: 36px;
  }
}
</style>
